<template>
  <div class="app-container">
    <!-- 输入表单 -->
    <el-form label-width="120px">
      <el-form-item label="新闻主题">
        <el-input v-model="news.subject" />
      </el-form-item>
      
      <el-form-item label="新闻热度">
        <el-input-number v-model="news.heat" :min="0"/>
      </el-form-item>
      <el-form-item label="新闻内容">
        <el-input v-model="news.content" type="textarea" :rows="5"/>
      </el-form-item>
      <el-form-item label="新闻图片">
        <el-upload
          :action="BASE_API + '/news/upload'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          class="avatar-uploader">
          <img v-if="news.picture" :src="news.picture" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <!-- 上传视频 -->
      <el-form-item label="上传视频">
        <el-upload
          ref="upload"
          :auto-upload="false"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :on-exceed="handleUploadExceed"
          :file-list="fileList"
          :limit="1"
          :before-remove="handleBeforeRemove"
          :on-remove="handleOnRemove"
          :action="BASE_API+'/news/uploadVideo'">
          <el-button slot="trigger" size="small" type="primary">选择视频</el-button>
          <el-button
            :disabled="uploadBtnDisabled"
            style="margin-left: 10px;"
            size="small"
            type="success"
            @click="submitUpload()">上传</el-button>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="saveOrUpdate()">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>


<script>
import news from "@/api/news/news";
import newsApi from "@/api/news/news";
export default {
    data() {
        return {
            BASE_API: 'http://localhost:8888',
            news:{
                heat: 0
            },
            uploadBtnDisabled: false
        }
    },
    created() {
      if(this.$route.params.id){
        const id = this.$route.params.id;
        this.fetchDataById(id)
      }
    },
    methods: {
      fetchDataById(id){
        newsApi.getNewsById(id)
        .then(response => {
          this.news = response.data
        })
      },
      //添加
      save(){
        newsApi.saveNews(this.news)
        .then((response) => {
            this.$message({
                type: 'success',
                message: '添加成功!'
            });
            //跳转列表页面
            this.$router.push({path:'/news/list'})
        })
      },
      //修改
      update(){
        newsApi.updateNews(this.news)
        .then((response) => {
            this.$message({
                type: 'success',
                message: '修改成功!'
            });
            //跳转列表页面
            this.$router.push({path:'/news/list'})
        })
      },
      saveOrUpdate(){
        if(this.news.id){
          this.update()
        }else{
          this.save()
        }
      },
      // 上传成功回调
      handleAvatarSuccess(res, file) {
        // console.log(res)
        if (res.code==20000) {
          // console.log(res)
          this.news.picture = res.data
          // 强制重新渲染
          this.$forceUpdate()
        } else {
          this.$message.error('上传失败 （非0）')
        }
      },

      // 错误处理
      handleAvatarError() {
        console.log('error')
        this.$message.error('上传失败（http失败）')
      },

      // 上传校验
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      },
      // 上传多于一个视频
      handleUploadExceed(files, fileList) {
        this.$message.warning('想要重新上传视频，请先删除已上传的视频')
      },
      // 上传
      submitUpload() {
        this.uploadBtnDisabled = true
        this.$refs.upload.submit() // 提交上传请求
      },
      // 视频上传成功的回调
      handleUploadSuccess(response, file, fileList) {
        this.uploadBtnDisabled = false
        this.news.video = response.data
        // this.video.videoOriginalName = file.name
      },
      // 失败回调
      handleUploadError() {
        this.uploadBtnDisabled = false
        this.$message.error('上传失败2')
      },
      // 删除视频文件确认
      handleBeforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`)
      },
      // 执行视频文件的删除
      handleOnRemove(file, fileList) {
        console.log("删除");
        // if (!this.video.videoSourceId) {
        //   return
        // }
        // vodApi.removeByVodId(this.video.videoSourceId).then(response => {
        //   this.video.videoSourceId = ''
        //   this.video.videoOriginalName = ''
        //   videoApi.updateById(this.video)
        //   this.$message.success(response.message)
        // })
      }
    },
    
}
</script>